package ProductorConsumerModel;

/**
 * @author 李泽伟
 */
public class Main {
    public static void main(String[] args) {
        Depository depository = new Depository();

        //创建生产者
        Productor productor = new Productor(depository);
        productor.setName("生产者1");
        //创建消费者
        Consumer consumer = new Consumer(depository);
        consumer.setName("消费者1");

        productor.start();
        consumer.start();
    }
}

/**
 * 生产者
 */
class Productor extends Thread{
    private Depository depository;

    public Productor(Depository depository) {
        this.depository = depository;
    }

    @Override
    public void run() {
        //生产
        System.out.println(getName()+"开始生产产品");
        while (true) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            depository.produce();
        }
    }
}
/**
 * 消费者
 */
class Consumer extends Thread{
    private Depository depository;

    public Consumer(Depository depository) {
        this.depository = depository;
    }
    @Override
    public void run() {
        System.out.println(getName()+"消费者开始消费产品");
        while (true){
            try {
                sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            depository.consume();
        }
    }
}
/**
 * 仓库
 */
class Depository{
    private int productNumber = 0;
    /**
     * 生产产品
     */
    public synchronized void produce() {
        if (productNumber < 20) {
            notify();
            productNumber++;
            System.out.println(Thread.currentThread().getName()+":开始生产第"+productNumber+"个产品");
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    /**
     * 消费产品
     */
    public synchronized void consume() {
        if (productNumber > 0) {
            System.out.println(Thread.currentThread().getName()+":开始消费第"+productNumber+"个产品");
            productNumber--;
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
